package com.hbnu.mysql.User;

import com.hbnu.mysql.Cart.OrderService;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Scanner;

/*
 * @author zouting
 * @Date 2025-11-26-12:57
 * 用户个人中心
 *
 */public class UserCenter {
    private final String loginUser;
    private final Scanner scanner;
    private final OrderService orderService;

    public UserCenter(String loginUser) {
        this.loginUser = loginUser;
        this.scanner = new Scanner(System.in);
        this.orderService = new OrderService(loginUser);
    }

    /**
     * 显示个人中心菜单
     */
    public void showMenu() {
        while (true) {
            System.out.println("\n========== 个人中心 ==========");
            System.out.println("1. 查看个人信息");
            System.out.println("2. 修改个人信息");
            System.out.println("3. 修改密码");
            System.out.println("4. 查看我的订单");
            System.out.println("5. 查看订单详情");
            System.out.println("6. 返回上一级");
            System.out.print("请选择操作(1-6): ");

            String choice = scanner.nextLine().trim();
            switch (choice) {
                case "1":
                    showUserInfo();
                    break;
                case "2":
                    updateUserInfo();
                    break;
                case "3":
                    changePassword();
                    break;
                case "4":
                    orderService.viewUserOrders();
                    break;
                case "5":
                    orderService.viewOrderDetail();
                    break;
                case "6":
                    return;
                default:
                    System.out.println("无效选择，请重新输入");
            }
        }
    }

    /**
     * 查看个人信息
     */
    private void showUserInfo() {
        String sql = "SELECT username, address, phone, role FROM tb_user WHERE username = ?";

        try (Connection conn = LRService.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {

            ps.setString(1, loginUser);
            ResultSet rs = ps.executeQuery();

            if (rs.next()) {
                System.out.println("\n========== 个人信息 ==========");
                System.out.println("用户名: " + rs.getString("username"));
                System.out.println("地址: " + (rs.getString("address") != null ? rs.getString("address") : "未设置"));
                System.out.println("手机号: " + (rs.getString("phone") != null ? rs.getString("phone") : "未设置"));
                String role = rs.getInt("role") == 1 ? "管理员" : "普通用户";
                System.out.println("角色: " + role);
                System.out.println("==============================");
            }

        } catch (Exception e) {
            System.out.println("获取用户信息失败: " + e.getMessage());
        }
    }

    /**
     * 修改个人信息
     */
    private void updateUserInfo() {
        showUserInfo();

        System.out.println("\n========== 修改个人信息 ==========");
        System.out.print("请输入新地址(直接回车保持原地址): ");
        String newAddress = scanner.nextLine().trim();

        System.out.print("请输入新手机号(直接回车保持原手机号): ");
        String newPhone = scanner.nextLine().trim();

        // 构建更新SQL
        StringBuilder sql = new StringBuilder("UPDATE tb_user SET ");
        boolean hasUpdate = false;

        if (!newAddress.isEmpty()) {
            sql.append("address = ?");
            hasUpdate = true;
        }

        if (!newPhone.isEmpty()) {
            if (hasUpdate) sql.append(", ");
            sql.append("phone = ?");
            hasUpdate = true;
        }

        if (!hasUpdate) {
            System.out.println("没有修改任何信息");
            return;
        }

        sql.append(" WHERE username = ?");

        try (Connection conn = LRService.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql.toString())) {

            int paramIndex = 1;
            if (!newAddress.isEmpty()) {
                ps.setString(paramIndex++, newAddress);
            }
            if (!newPhone.isEmpty()) {
                ps.setString(paramIndex++, newPhone);
            }
            ps.setString(paramIndex, loginUser);

            int rowsAffected = ps.executeUpdate();
            if (rowsAffected > 0) {
                System.out.println("个人信息更新成功！");
                showUserInfo(); // 显示更新后的信息
            } else {
                System.out.println("更新失败，请重试");
            }

        } catch (Exception e) {
            System.out.println("修改个人信息失败: " + e.getMessage());
        }
    }

    /**
     * 修改密码
     */
    private void changePassword() {
        System.out.println("\n========== 修改密码 ==========");
        System.out.print("请输入当前密码: ");
        String currentPassword = scanner.nextLine().trim();
        System.out.print("请输入新密码: ");
        String newPassword = scanner.nextLine().trim();
        System.out.print("请确认新密码: ");
        String confirmPassword = scanner.nextLine().trim();

        if (!newPassword.equals(confirmPassword)) {
            System.out.println("两次输入的新密码不一致");
            return;
        }

        if (newPassword.length() < 6) {
            System.out.println("新密码长度不能少于6位");
            return;
        }

        // 验证当前密码
        String verifySql = "SELECT password FROM tb_user WHERE username = ?";
        String updateSql = "UPDATE tb_user SET password = ? WHERE username = ? AND password = ?";

        try (Connection conn = LRService.getConnection()) {
            // 验证当前密码
            try (PreparedStatement verifyPs = conn.prepareStatement(verifySql)) {
                verifyPs.setString(1, loginUser);
                ResultSet rs = verifyPs.executeQuery();
                if (rs.next() && !currentPassword.equals(rs.getString("password"))) {
                    System.out.println("当前密码错误");
                    return;
                }
            }

            // 更新密码
            try (PreparedStatement updatePs = conn.prepareStatement(updateSql)) {
                updatePs.setString(1, newPassword);
                updatePs.setString(2, loginUser);
                updatePs.setString(3, currentPassword);

                int rowsAffected = updatePs.executeUpdate();
                if (rowsAffected > 0) {
                    System.out.println("密码修改成功！");
                } else {
                    System.out.println("密码修改失败，请检查当前密码是否正确");
                }
            }

        } catch (Exception e) {
            System.out.println("修改密码失败: " + e.getMessage());
        }
    }

}
